<?php
/**
 * Plugin Color: Sets new colors for text and background.
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Christopher Smith <chris@jalakai.co.uk>
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
require_once(DOKU_PLUGIN.'uniaction/utilityfunctions.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_uniaction extends DokuWiki_Syntax_Plugin {

	/**
	 * return some info
	 */
	function getInfo(){
		return array(
            'author' => 'Benjamin Eckstein',
            'email'  => 'umingo@googlemail.com',
            'date'   => '2011-08-06',
            'name'   => 'Sommer Uni Menu',
            'desc'   => 'Creates Sidenav Menu',
            'url'    => 'http://www.umingo.de',
		);
	}

	function getType(){ return 'formatting'; }
	function getAllowedTypes() { return array('formatting', 'substition', 'disabled'); }
	function getSort(){ return 158; }
	function connectTo($mode) { $this->Lexer->addEntryPattern('<uniaction.*?>(?=.*?</uniaction>)',$mode,'plugin_uniaction'); }
	function postConnect() { $this->Lexer->addExitPattern('</uniaction>','plugin_uniaction'); }

	function getPType(){ return 'block';
	}

	/**
	 * Handle the match
	 */
	function handle($match, $state, $pos, &$handler){
			
		switch ($state) {
			case DOKU_LEXER_ENTER :
				//prepare data for renderer
				return array($state, array($color, $background));

			case DOKU_LEXER_UNMATCHED :  return array($state, $match);
			case DOKU_LEXER_EXIT :       return array($state, '');
		}
		return array();
	}

	/**
	 * Create output
	 */
	function render($mode, &$renderer, $data) {
		if($mode == 'xhtml'){
			list($state,$match) = $data;
			switch ($state) {
				case DOKU_LEXER_ENTER :
					break;

				case DOKU_LEXER_UNMATCHED :
					$str = "";
					if($match == "anmeldung")
					{
						$str .= uni_checkForRegistration();
					}
					elseif($match == "meineKurse")
					{
						$str .= showMyProgramm();
					}
					elseif($match == "kurse")
					{
						$str .= showProgramm();
					}
					elseif($match == "vorlesungen")
					{
						$str .= showProgramm2();
					}
					elseif($match == "login")
					{
						$str .= showLogin();
					}			
					elseif($match == "archiv")
					{
						$str .= showArchive();
					}
			
					elseif($match == "myfotos")
					{
						$str .= "Zur Zeit noch nicht implementiert!";
					}
					elseif($match == "mydata")
					{
						$str .= "Zur Zeit noch nicht implementiert!";
					}
					elseif($match == "xyz"){

					}
					//match is the text within the <menu> </menu> part
					$renderer->doc .= $str;
					break;
				case DOKU_LEXER_EXIT :
					break;
			}
			return true;
		}
		return false;
	}
}

function uni_checkForRegistration(){

	//is form submitted?
	if(!isset($_POST['vname'],$_POST['name'],$_POST['schule'],$_POST['phone'],$_POST['mail'])){
		return "";//do nothing because formular is incomplete or not submitted
	}
	//gather data from formular and ESCAPE
	$vname = trim(htmlspecialchars($_POST['vname'], ENT_QUOTES));
	$name = trim(htmlspecialchars( $_POST['name'], ENT_QUOTES));
	$schule = trim(htmlspecialchars($_POST['schule'], ENT_QUOTES));
	$phone = trim(htmlspecialchars($_POST['phone'], ENT_QUOTES));
	$email = trim(htmlspecialchars($_POST['mail'], ENT_QUOTES));

	//check if valid or return error
	if(strlen($vname) > 50 || strlen($name) > 50 || strlen($schule) > 50 || strlen($phone) > 50 )
	return "<b style='color:red'>Eingabedaten sind fehlerhaft oder zu lang.</b>";

	if($email == "" || $vname = "" || $name == ""){
		return "<b style='color:red'>Bitte alle benötigten Angaben machen (Vorname, Name, Emailadresse).</b>";
	}
	
	
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))
	return "<b style='color:red'>Bitte eine gültige Emailadresse angeben!</b>";

	//does the email already exist?
	$db = getDBConnection();
	$query = sprintf("SELECT id from schueler where email='%s'", mysql_real_escape_string($email));
	$result = doQuery($query);
	if($result === FALSE) return "<b style='color:red'>Probleme mit der Datenbank, wir bitten um Entschuldigung</b>";
	$array = mysql_fetch_assoc($result);
	if($array !== FALSE) return "<b style='color:red'>Diese Email existiert bereits!</b>";;

	//registrate user and return success
	$password = createRandomPassword();
	$passwordHash = hash_password($password,$email);
	$query = "INSERT INTO schueler SET name = '%s', vname = '%s',schule = '%s',phone = '%s',email = '%s', password='$passwordHash'";
	$query = sprintf($query, mysql_real_escape_string($name),mysql_real_escape_string($vname),mysql_real_escape_string($schule),mysql_real_escape_string($phone),mysql_real_escape_string($email));
	doQuery($query);

	$out = "<b  style='color:green'>Du hast dich erfolgreich registriert, dein Passwort (DEBUG:$password) wird in kürzer per Email verschickt.</b>";
	//send email with password
	if(!@send_welcome_email($vname." ".$name,$password,$email)){
		$out .="<br><b style='color:red'>Deine Email konnte nicht erfolgreich verschickt werden, bitte wende dich an das Sommeruni Team!</b>";
	}

	return $out;
}
function send_welcome_email($name,$password,$email){
	//TODO IMPLEMENT EMAIL AND ADD NICE TEXT !!

	// Die Nachricht
$nachricht = "Hallo $name, 

willkommen bei der Sommeruni der Freien Universität Berlin. 
Um dich anzumelden benutze bitte deine Emailadresse und das folgende Passwort: 

Email: $email
Passwort: $password

Viele Grüße 
Das Sommeruni Team";

$empfaenger = $email;
$betreff = 'Willkommen bei der Sommeruni der FU';
$header = 'From: sommerun@zedat.fu-berlin.de' . "\r\n" .
    'Reply-To: sommerun@zedat.fu-berlin.de' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

return @mail($empfaenger, $betreff, $nachricht, $header);


// Send
mail('benutzer@example.com', 'Mein Betreff', $nachricht);
	
}
?>